import CryptoJS from 'crypto-js'

export default {
	//随机生成指定数量的16进制key
	generatekey(num) {
		let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		let key = "";
		for (var i = 0; i < num.length; i++) {
			let randomPoz = Math.floor(Math.random() * library.length);
			key += library.substring(randomPoz, randomPoz + 1);
		}
		return key;
	},

	//加密
	encrypt(word, keyStr) {
		keyStr = keyStr ? keyStr : "abcdsxyzhkj12345";
		let key = CryptoJS.enc.Utf8.parse(keyStr);
		var iv = CryptoJS.enc.Utf8.parse(keyStr);

		let srcs = CryptoJS.enc.Utf8.parse(word);

		let encrypted = CryptoJS.AES.encrypt(srcs, key, {
			iv: iv,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
	},

	//解密
	decrypt(word, keyStr) {
		word = (word + '').replace(/\n*$/g, '').replace(/\n/g, '');
		keyStr = keyStr ? keyStr : "abcdsxyzhkj12345";
		var key = CryptoJS.enc.Utf8.parse(keyStr);
		var iv = CryptoJS.enc.Utf8.parse(keyStr);

		let base64 = CryptoJS.enc.Base64.parse(word)
		let src = CryptoJS.enc.Base64.stringify(base64)

		var decrypt = CryptoJS.AES.decrypt(src, key, {
			iv: iv,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
		return decryptedStr.toString()
	}


}
